using Microsoft.AspNetCore.Mvc;
using Traceability.API.Dtos;
using Traceability.API.Services;
using Traceability.ErrorCode;

namespace Traceability.API.Controllers
{
    /// <summary>
    /// 图片验证码控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class CaptchaController : ControllerBase
    {
        private readonly HybridCaptchaService _hybridCaptchaService;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="hybridCaptchaService">混合验证码服务</param>
        public CaptchaController(HybridCaptchaService hybridCaptchaService)
        {
            _hybridCaptchaService = hybridCaptchaService;
        }

        /// <summary>
        /// 获取图片验证码
        /// </summary>
        /// <returns>验证码图片和ID</returns>
        [HttpGet]
        public async Task<ActionResult<APIResult<CaptchaDto>>> GetCaptcha()
        {
            try
            {
                var (captchaId, imageBytes, expireTime) = await _hybridCaptchaService.GenerateCaptchaAsync();
                var imageBase64 = $"data:image/png;base64,{Convert.ToBase64String(imageBytes)}";

                var captchaDto = new CaptchaDto
                {
                    CaptchaId = captchaId,
                    ImageBase64 = imageBase64,
                    CreateTime = DateTime.Now,
                    ExpireTime = expireTime
                };

                return new APIResult<CaptchaDto>
                {
                    Code = APIEnum.操作成功,
                    Message = $"获取验证码成功 (存储类型: {_hybridCaptchaService.GetCurrentStorageType()})",
                    Data = captchaDto
                };
            }
            catch (Exception ex)
            {
                return new APIResult<CaptchaDto>
                {
                    Code = APIEnum.操作失败,
                    Message = $"获取验证码失败: {ex.Message}"
                };
            }
        }

        /// <summary>
        /// 获取图片验证码（图片流，Swagger可直接预览）
        /// </summary>
        /// <remarks>
        /// 直接返回图片流，Content-Type: image/png，Swagger响应区可直接显示图片。
        /// 验证码ID将在响应头中返回: X-Captcha-Id
        /// </remarks>
        /// <returns>验证码图片流</returns>
        [HttpGet("Image")]
        public async Task<IActionResult> GetCaptchaImage()
        {
            try
            {
                var (captchaId, imageBytes, _) = await _hybridCaptchaService.GenerateCaptchaAsync();

                // 将验证码ID添加到响应头
                Response.Headers.Add("X-Captcha-Id", captchaId);
                Response.Headers.Add("X-Storage-Type", _hybridCaptchaService.GetCurrentStorageType());

                return File(imageBytes, "image/png");
            }
            catch (Exception ex)
            {
                return BadRequest($"获取验证码失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 校验图片验证码
        /// </summary>
        /// <param name="dto">验证码校验请求</param>
        /// <returns>校验结果</returns>
        [HttpPost]
        public async Task<ActionResult<APIResult<bool>>> VerifyCaptcha([FromBody] CaptchaVerifyDto dto)
        {
            try
            {
                if (string.IsNullOrEmpty(dto.CaptchaId) || string.IsNullOrEmpty(dto.CaptchaCode))
                {
                    return new APIResult<bool>
                    {
                        Code = APIEnum.操作失败,
                        Message = "验证码ID和验证码不能为空",
                        Data = false
                    };
                }

                bool isValid = await _hybridCaptchaService.ValidateCaptchaAsync(dto.CaptchaId, dto.CaptchaCode);

                return new APIResult<bool>
                {
                    Code = isValid ? APIEnum.操作成功 : APIEnum.操作失败,
                    Message = isValid ? "验证码验证成功" : "验证码验证失败",
                    Data = isValid
                };
            }
            catch (Exception ex)
            {
                return new APIResult<bool>
                {
                    Code = APIEnum.操作失败,
                    Message = $"验证码验证失败: {ex.Message}",
                    Data = false
                };
            }
        }

        /// <summary>
        /// 检查验证码服务健康状态
        /// </summary>
        /// <returns>健康状态信息</returns>
        [HttpGet]
        public async Task<ActionResult<APIResult<object>>> HealthCheck()
        {
            try
            {
                bool redisHealthy = await _hybridCaptchaService.CheckRedisHealthAsync();
                string currentStorage = _hybridCaptchaService.GetCurrentStorageType();

                var healthInfo = new
                {
                    RedisHealthy = redisHealthy,
                    CurrentStorageType = currentStorage,
                    Timestamp = DateTime.Now
                };

                return new APIResult<object>
                {
                    Code = APIEnum.操作成功,
                    Message = $"验证码服务运行正常，当前使用: {currentStorage}",
                    Data = healthInfo
                };
            }
            catch (Exception ex)
            {
                return new APIResult<object>
                {
                    Code = APIEnum.操作失败,
                    Message = $"健康检查失败: {ex.Message}"
                };
            }
        }
    }
}